package com.jilefojing.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jgshun
 * @date 2016-3-1 下午4:52:36
 * @version 1.0
 */
public class AESCoder {

	private static final Logger _LOGGER = LoggerFactory.getLogger(AESCoder.class);

	private final static String _DEFAULT_KEY = "TWrGEzLcN9WkrvTf0CTw9g==";

	/**
	 * 秘钥算法
	 */
	private static final String KEY_ALGORITHM = "AES";
	/**
	 * 加密/揭秘算法 / 工作模式 / 填充方式 java7 支持 PCKCS5OADDING
	 */
	private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	/**
	 * 转换密钥
	 * 
	 * @param key
	 *            二进制秘钥
	 * @return
	 */
	private static Key toKey(byte[] key) {
		// 实例化aes 秘钥材料
		SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
		return secretKey;
	}

	/**
	 * 解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		// 还原密钥
		Key k = toKey(key);
		/**
		 * 实例化 使用pkcs7padding 填充方式 安如下方式实现 cipher.getInstance(CIPHER_ALGORITHM,
		 * "BC");
		 */

		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
		} catch (NoSuchProviderException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		// 初始化,解密模式
		cipher.init(Cipher.DECRYPT_MODE, k);
		// 执行操作
		return cipher.doFinal(data);
	}

	/***
	 * 解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws InvalidKeyException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws UnsupportedEncodingException
	 */
	// public static String decrypt(String data, String key)
	// throws NoSuchAlgorithmException, NoSuchPaddingException,
	// InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
	// UnsupportedEncodingException {
	// byte[] ret = decrypt(data.getBytes("utf-8"), key.getBytes("utf-8"));
	// return new String(ret, "utf-8");
	// }

	/**
	 * 默认加密
	 * 
	 * @param data
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws InvalidKeyException
	 */
	public static String defaultEncrypt(String data) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
		try {
			return new String(Base64.encodeBase64(encrypt(data.getBytes("UTF8"), Base64.decodeBase64(_DEFAULT_KEY.getBytes("UTF8")))), "UTF8");
		} catch (UnsupportedEncodingException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 默认解密
	 * 
	 * @param data
	 * @return
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 */
	public static String defaultDecrypt(String data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		try {
			return new String(decrypt(Base64.decodeBase64(data.getBytes("UTF8")), Base64.decodeBase64(_DEFAULT_KEY.getBytes("UTF8"))), "UTF8");
		} catch (UnsupportedEncodingException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param data
	 *            代加密的数据
	 * @param key
	 *            密钥
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 * @throws InvalidKeyException
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
		Key k = toKey(key);
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
		} catch (NoSuchProviderException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return cipher.doFinal(data);
	}

	/**
	 * 动态 生成密钥
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static byte[] initKey() throws NoSuchAlgorithmException {
		// 实例化
		KeyGenerator kg = null;
		try {
			kg = KeyGenerator.getInstance(KEY_ALGORITHM, "BC");
		} catch (NoSuchProviderException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		// aes要求密钥 长度 128位,192位,或者256
		kg.init(128);
		// 生成密钥
		SecretKey secretKey = kg.generateKey();
		// 获取密钥的二进制编码形式
		return secretKey.getEncoded();
	}

	/**
	 * 初始化密钥,得到密钥的字符串形式
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String initKeyString() throws NoSuchAlgorithmException {
		try {
			return new String(Base64.encodeBase64(initKey()), "UTF8");
		} catch (UnsupportedEncodingException e) {
			_LOGGER.error(e.getMessage(), e);
		}
		return null;
		// return Base64.encodeBase64String();
	}

	/**
	 * 返回密钥
	 * 
	 * @param key
	 * @return
	 */
	public static byte[] getKey(String key) {
		return Base64.decodeBase64(key);
	}

	/**
	 * 摘要处理
	 * 
	 * @param data
	 * @return
	 */
	public static String shaHex(byte[] data) {
		return DigestUtils.md5Hex(data);
	}

	/**
	 * 验证
	 * 
	 * @param data
	 * @param messageDigest
	 * @return
	 */
	public static boolean validate(byte[] data, String messageDigest) {
		return messageDigest.equals(shaHex(data));
	}

	public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {

		Date date = new Date();
		date.setTime(date.getTime() + 30 * 1000);
		Date nowDate = new Date();
		DateFormat cc = new SimpleDateFormat("yyyyMMddHHmmss");

		System.out.println("=======================" + cc.format(date) + "===============" + cc.format(nowDate));

		String inputStr = "13721110915_false_2_" + nowDate.getTime();
		byte[] inputData = inputStr.getBytes();
		System.out.println("原文:\t" + inputStr);
		// byte[] key = AESCoder.initKey();
		byte[] key = Base64.decodeBase64("Pbbntdx/41MWPCS3MlOg5A==");

		System.out.println("密钥:\t" + Base64.encodeBase64String(key));
		// // 加密
		inputData = AESCoder.encrypt(inputData, key);
		System.out.println("加密后:\t" + URLEncoder.encode(Base64.encodeBase64String(inputData)));
		// // 解密
		// byte[] outputData = AESCoder.decrypt(inputData, key);
		// System.out.println("解密后:\t" + new String(outputData));

		// System.out.println("密钥:\t" + _DEFAULT_KEY);
		// String enc = URLEncoder.encode(defaultEncrypt(inputStr), "UTF-8");
		// System.out.println(enc);
		// System.out.println(defaultDecrypt(URLDecoder.decode(enc, "UTF-8")));

	}
}
